package com.tong.lib.retrofit;

import com.tong.lib.retrofit.okhttp.HttpConfig;
import com.tong.lib.retrofit.okhttp.InterceptorUtil;
import com.tong.lib.utils.AppContextUtil;

import java.io.File;
import java.util.concurrent.TimeUnit;

import hjt.com.componentbase.retrofit.RetrofitService;
import okhttp3.Cache;
import okhttp3.OkHttpClient;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;
import retrofit2.converter.scalars.ScalarsConverterFactory;

/**
 * Created by Tong on 2018/4/20.
 */

public class RetrofitUtils {

    private static RetrofitService mRetrofitService = null;

    private RetrofitUtils() {
    }

    //单例模式
    public static RetrofitService init() {
        if (mRetrofitService == null) {
            synchronized (RetrofitUtils.class) {
                if (mRetrofitService == null) {
                    Retrofit build = new Retrofit.Builder().client(initOkHttp())
                            .baseUrl(HttpConfig.BASE_URL)
                            .addConverterFactory(ScalarsConverterFactory.create())//添加String转换器
                            .addConverterFactory(GsonConverterFactory.create())//添加gson转换器
                            .addCallAdapterFactory(RxJava2CallAdapterFactory.create())//添加rxjava转换器
                            .build();
                    mRetrofitService = build.create(RetrofitService.class);
                }
            }
        }
        return mRetrofitService;
    }

    private static OkHttpClient initOkHttp() {
        //缓存
        File cacheFile = new File(AppContextUtil.getContext().getCacheDir(), "cache");
        Cache cache = new Cache(cacheFile, 1024 * 1024 * 100); //100Mb
        return new OkHttpClient.Builder().connectTimeout(HttpConfig.HTTP_CONNECT_TIME, TimeUnit.SECONDS)//设置连接超时时间
                .readTimeout(HttpConfig.HTTP_READ_TIME, TimeUnit.SECONDS)//设置读取超时时间
                .writeTimeout(HttpConfig.HTTP_WRITE_TIME, TimeUnit.SECONDS)//设置写入超时时间
                .addInterceptor(InterceptorUtil.headerInterceptor())//增加头部信息
                .addInterceptor(InterceptorUtil.LogInterceptor())//添加日志拦截器
                .retryOnConnectionFailure(true).readTimeout(HttpConfig.RETRY_COUNT, TimeUnit.SECONDS)//请求失败重连次数
                .cache(cache).build();
    }


}
